#pragma once

// This class implements the IWriteStream
// interface on top of a Windows file.
class CWriteStreamOnFile :
	public IWriteStream
{
public:

	HRESULT Initialize(LPCTSTR szFileName, bool append)
	{
		HRESULT hr;
		if(FAILED(hr=m_file.Create(szFileName, GENERIC_WRITE,
					FILE_SHARE_READ, append?OPEN_ALWAYS:CREATE_ALWAYS)))
			return hr;
		if(FAILED(hr=m_file.Seek(0, FILE_END)))
			return hr;
	}

	HRESULT WriteStream(LPCSTR szOut, int nLen, LPDWORD pdwWritten)
	{
		if (nLen < 0)
		{
			nLen = (int) strlen(szOut);
		}

		DWORD dwWritten = 0;
		HRESULT hr = m_file.Write(szOut, nLen, &dwWritten);
		if (pdwWritten)
		{
			*pdwWritten = dwWritten;
		}

		return hr;
	}

	HRESULT FlushStream()
	{
		if (FlushFileBuffers(m_file))
		{
			return S_OK;
		}
		return AtlHresultFromLastError();
	}

private:
	CAtlFile m_file;
};



